import React, { PureComponent, Fragment } from 'react';
import { Card, Form, Row, Input, Button, Table, Divider, Popconfirm, message, Popover, Select, Modal, Tooltip } from 'antd';
import { connect } from 'dva';
import lodash from 'lodash';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import PermissionManageAdd from './PermissionManageAdd';
import PermissionManageUpdate from './PermissionManageUpdate';
import Ellipsis from '../../components/Ellipsis';
import {
  SorterOrderMapper,
  ResourcesTypeMapper,
  TargetExistMapper,
  NeedAuthorizationMapper,
  ResourcesTypeArray,
  NeedAuthorizationArray,
  TargetExistArray,
} from '../../utils/enum';
import { cutOffStr } from '../../utils/utils';
// import classNames from 'classnames';
import styles from './PermissionManage.less';

@connect(({ PermissionManageModel, GlobalEnumModel, loading }) => ({
  PermissionManageModel,
  GlobalEnumModel,
  queryLoading: loading.effects['PermissionManageModel/findByPage'],
  addPermissionLoading: loading.effects['PermissionManageModel/addPermission'],
  getPermissionModelLoading: loading.effects['PermissionManageModel/getPermissionModel'],
  updatePermissionLoading: loading.effects['PermissionManageModel/updatePermission'],
}))
@Form.create()
export default class PermissionManage extends PureComponent {

  // 数据初始化
  componentDidMount() {
    this.findByPage();
  }

  // 查询数据
  findByPage = (e) => {
    if (e) e.preventDefault();
    const { dispatch, form } = this.props;
    const queryParam = form.getFieldsValue();
    dispatch({ type: 'GlobalEnumModel/allSysName' });
    dispatch({ type: 'PermissionManageModel/findByPage', payload: { ...queryParam, pageNo: 0 } });
    dispatch({ type: 'PermissionManageModel/save', payload: { selectedRowKeys: [] } });
  }

  // 表格数据过滤或跳页
  handleTableChange = (pagination, _, sorter) => {
    const { dispatch, PermissionManageModel } = this.props;
    const queryParam = { ...PermissionManageModel.queryParam, pageNo: pagination.current, pageSize: pagination.pageSize };
    // 排序
    if (sorter.field) {
      const sorterMapper = {};
      queryParam.orderField = sorterMapper[sorter.field];
      queryParam.sort = SorterOrderMapper[sorter.order];
    } else {
      queryParam.orderField = undefined;
      queryParam.sort = undefined;
    }
    dispatch({ type: 'PermissionManageModel/findByPage', payload: queryParam });
  }

  // 查询表单
  queryForm() {
    const { form: { getFieldDecorator }, queryLoading, PermissionManageModel: { queryParam }, GlobalEnumModel: { sysNameList } } = this.props;
    return (
      <Form onSubmit={this.findByPage} layout="inline" className={styles.queryForm}>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="所属系统">
            {getFieldDecorator('sysName', { initialValue: queryParam.sysName })(
              <Select placeholder="所属系统" allowClear={true}>
                {sysNameList.map(sysName => (<Select.Option key={sysName} value={sysName}>{sysName}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="权限标题">
            {getFieldDecorator('title', { initialValue: queryParam.title })(
              <Input placeholder="权限标题(模糊匹配)" />
            )}
          </Form.Item>
          <Form.Item label="权限类型">
            {getFieldDecorator('resourcesType', { initialValue: queryParam.resourcesType })(
              <Select placeholder="权限类型" allowClear={true}>
                {ResourcesTypeArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="权限标识">
            {getFieldDecorator('permissionStr', { initialValue: queryParam.permissionStr })(
              <Input placeholder="权限标识(模糊匹配)" />
            )}
          </Form.Item>
        </Row>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="目标Class">
            {getFieldDecorator('targetClass', { initialValue: queryParam.targetClass })(
              <Input placeholder="目标Class(模糊匹配)" />
            )}
          </Form.Item>
          <Form.Item label="目标方法">
            {getFieldDecorator('targetMethod', { initialValue: queryParam.targetMethod })(
              <Input placeholder="目标方法(模糊匹配)" />
            )}
          </Form.Item>
          <Form.Item label="资源URL">
            {getFieldDecorator('resourcesUrl', { initialValue: queryParam.resourcesUrl })(
              <Input placeholder="资源URL(模糊匹配)" style={{ width: 455 }} />
            )}
          </Form.Item>
        </Row>
        <Row gutter={{ md: 0, lg: 0, xl: 0 }}>
          <Form.Item label="目标存在">
            {getFieldDecorator('targetExist', { initialValue: queryParam.targetExist })(
              <Select placeholder="目标存在" allowClear={true}>
                {TargetExistArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item label="需要授权">
            {getFieldDecorator('needAuthorization', { initialValue: queryParam.needAuthorization })(
              <Select placeholder="需要授权" allowClear={true}>
                {NeedAuthorizationArray.map(item => (<Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>))}
              </Select>
            )}
          </Form.Item>
          <Form.Item className={styles.formItemButton}>
            <Button type="primary" htmlType="submit" disabled={queryLoading}>查询</Button>
          </Form.Item>
        </Row>
      </Form>
    );
  }

  // 功能按钮
  actionButton() {
    const { dispatch, PermissionManageModel: { selectedRowKeys }, queryLoading } = this.props;
    const disabled = queryLoading || (selectedRowKeys && selectedRowKeys.length <= 0);
    return (
      <Fragment>
        <Button.Group style={{ marginBottom: 8 }}>
          <Button
            icon="plus-circle"
            onClick={() => {
              dispatch({ type: 'GlobalEnumModel/allSysName' });
              dispatch({ type: 'PermissionManageModel/save', payload: { showAddPermission: true } });
            }}
          >
            新增
          </Button>
          <Button
            disabled={disabled}
            icon="minus-circle"
            onClick={() => {
              const modal = Modal.confirm({
                title: (<span style={{ color: undefined }}>{`确定要删除选中的${selectedRowKeys.length}个权限?`}</span>),
                content: (
                  <Fragment>
                    建议不要删除存在的URL资源
                    <br />
                    这可能会导致未知错误
                  </Fragment>
                ),
                okText: '删除',
                cancelText: '取消',
                maskClosable: true,
                onOk: () => {
                  dispatch({
                    type: 'PermissionManageModel/delPermissionModels',
                    payload: { permissionSet: selectedRowKeys },
                    successCallBack: result => {
                      modal.destroy();
                      message.success(`权限删除成功 -> ${result.length}个`);
                    },
                  });

                },
                onCancel: () => modal.destroy(),
              });
            }}
          >
            删除
          </Button>
        </Button.Group>
      </Fragment>
    );
  }

  // 获取url权限信息
  getUrlPermissionInfo = (permission) => {
    const { resourcesUrl, targetClass, targetMethod } = permission;
    let { targetExist, needAuthorization, targetMethodParams, resourcesType } = permission;
    resourcesType = ResourcesTypeMapper[resourcesType];
    if (!resourcesType) resourcesType = ResourcesTypeMapper.error;
    if(!targetClass) return <span>{resourcesType.label}</span>;
    targetExist = TargetExistMapper[targetExist]
    if (!targetExist) targetExist = TargetExistMapper.error;
    needAuthorization = NeedAuthorizationMapper[needAuthorization];
    if (!needAuthorization) needAuthorization = NeedAuthorizationMapper.error;
    if (lodash.trim(targetMethodParams) !== "") {
      const params = lodash.split(targetMethodParams, ',');
      targetMethodParams = [];
      params.forEach(item => {
        let param = item;
        if (param.lastIndexOf('.') !== -1) {
          param = param.substring(param.lastIndexOf('.') + 1);
        }
        targetMethodParams.push(lodash.trim(param));
      });
      targetMethodParams = targetMethodParams.join(', ');
    } else {
      targetMethodParams = '--';
    }
    const packageStr = targetClass.substring(0, targetClass.lastIndexOf('.'));
    const classStr = targetClass.substring(targetClass.lastIndexOf('.') + 1);
    const labelStyle = { display: 'inline-block', width: 100 };
    const valueStyle = {};
    const content = (
      <div>
        <div>
          <span style={labelStyle}>URL地址</span>
          <span style={valueStyle}>{resourcesUrl}</span>
        </div>
        <div>
          <span style={labelStyle}>资源存在</span>
          <span style={{ ...valueStyle, color: targetExist.color }}>{targetExist.label}</span>
        </div>
        <div>
          <span style={labelStyle}>需要权限拦截</span>
          <span style={{ ...valueStyle, color: needAuthorization.color }}>{needAuthorization.label}</span>
        </div>
        <div>
          <span style={labelStyle}>代码 package</span>
          <span style={valueStyle}>{packageStr}</span>
        </div>
        <div>
          <span style={labelStyle}>代码 class</span>
          <span style={valueStyle}>{classStr}</span>
        </div>
        <div>
          <span style={labelStyle}>代码方法名</span>
          <span style={valueStyle}>{targetMethod}</span>
        </div>
        <div>
          <span style={labelStyle}>方法参数</span>
          <span style={valueStyle}>{targetMethodParams}</span>
        </div>
      </div>
    );
    return (
      <Popover placement="right" title={`URL权限详情 - {${permission.title}}`} content={content}>
        <a color={resourcesType.color}>{resourcesType.label}</a>
      </Popover>
    );
  }

  // 数据表格
  getTable() {
    const { dispatch, PermissionManageModel, queryLoading } = this.props;
    const columns = [
      { title: '系统名称', dataIndex: 'sysName', width: 130, render: val => <Ellipsis title={val} lines={1}>{val}</Ellipsis> },
      {
        title: '标题', dataIndex: 'title', width: 260,
        render: val => {
          return <Ellipsis title={val} lines={1}>{val}</Ellipsis>;
          // const label = cutOffStr(val, 34);
          // return <a title={val === label ? undefined : val}>{label}</a>;
        },
      },
      {
        title: '标识', dataIndex: 'permissionStr', width: 220,
        render: val => {
          return <Ellipsis title={val} lines={1}>{val}</Ellipsis>;
          // const label = cutOffStr(val, 29);
          // return <span title={val === label ? undefined : val}>{label}</span>;
        },
      },
      {
        title: '类型', dataIndex: 'resourcesType', width: 95,
        render: (val, record) => {
          let resourcesType = ResourcesTypeMapper[val];
          if (!resourcesType) resourcesType = ResourcesTypeMapper.error;
          if (lodash.indexOf([1], val) !== -1) {
            return this.getUrlPermissionInfo(record);
          } else {
            return resourcesType.label;
          }
        },
      },
      {
        title: 'URL资源地址', dataIndex: 'resourcesUrl', width: 280,
        render: (val, record) => {

          if (!val) return '-';
          const label = cutOffStr(val, 35);
          const needAuthorization = record.needAuthorization === 1;
          return (
            <Tooltip placement="right" title={`已${needAuthorization ? '开启' : '关闭'}授权 - 点击${needAuthorization ? '关闭' : '开启'}`}>
              <span
                title={val === label ? undefined : val}
                style={{ color: (needAuthorization ? '#52c41a' : '#faad14'), cursor: 'pointer' }}
                onClick={() => {
                  dispatch({
                    type: 'PermissionManageModel/updatePermission',
                    payload: { oldPermissionStr: record.permissionStr, needAuthorization: needAuthorization ? 2 : 1 },
                    successCallBack: result => {
                      message.success(`切换成功 -> ${result.needAuthorization === 1 ? '开启' : '关闭'}授权[${result.resourcesUrl}]`);
                    },
                  });
                }}
              >
                {label}
              </span>
            </Tooltip>
          );
        },
      },
      {
        title: '说明', dataIndex: 'description', width: 150,
        render: val => {
          return <Ellipsis title={val} lines={1}>{val}</Ellipsis>;
        },
      },
      { title: '创建时间', dataIndex: 'createAt', width: 140, render: val => <Ellipsis title={val} lines={1}>{val}</Ellipsis> },
      // { title: '更新时间', dataIndex: 'updateAt', width: 150, render: val => <Ellipsis title={val} lines={1}>{val}</Ellipsis> },
      {
        title: '操作', align: 'center', key: 'action', width: 120,
        render: (_, record) => (
          <Fragment>
            <a
              onClick={() => {
                dispatch({ type: 'GlobalEnumModel/allSysName' });
                dispatch({ type: 'PermissionManageModel/save', payload: { updatePermissionData: record, showUpdatePermission: true } });
                dispatch({ type: 'PermissionManageModel/getPermissionModel', payload: { permissionStr: record.permissionStr } });
              }}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <Popconfirm
              placement="left"
              title={`确定删除该权限(${record.title})?`}
              okText="删除"
              cancelText="取消"
              onConfirm={() => {
                const selectedRowKeys = lodash.filter(PermissionManageModel.selectedRowKeys, permissionStr => permissionStr !== record.permissionStr);
                dispatch({
                  type: 'PermissionManageModel/delPermissionModel',
                  payload: { permissionStr: record.permissionStr },
                  successCallBack: result => {
                    message.success(`权限删除成功 -> ${result.title}`);
                    dispatch({ type: 'PermissionManageModel/save', payload: { selectedRowKeys } });
                  },
                });
              }}
            >
              <a>删除</a>
            </Popconfirm>
          </Fragment>
        ),
      },
    ];
    return (
      <Table
        size="middle"
        bordered={true}
        rowKey={record => record.permissionStr}
        rowSelection={{
          fixed: false,
          selectedRowKeys: PermissionManageModel.selectedRowKeys,
          onChange: (_, selectedRows) => {
            const max = 50;
            if (selectedRows.length > max) {
              message.warning(`最多只能选择${max}个权限，当前选择${selectedRows.length}个`);
              return;
            }
            const selectedRowKeys = selectedRows.map(item => item.permissionStr);
            dispatch({ type: 'PermissionManageModel/save', payload: { selectedRowKeys } });
          },
        }}
        columns={columns}
        loading={queryLoading}
        dataSource={PermissionManageModel.data}
        pagination={PermissionManageModel.pagination}
        onChange={this.handleTableChange}
      />
    );
  }

  render() {
    const { dispatch, addPermissionLoading, getPermissionModelLoading, updatePermissionLoading, PermissionManageModel, GlobalEnumModel } = this.props;
    return (
      // const { dispatch, RoleManageModel } = this.props;
      <PageHeaderLayout>
        <Card bordered={false}>
          <div>
            {this.queryForm()}
          </div>
          {this.actionButton()}
          {this.getTable()}
        </Card>
        <PermissionManageAdd
          permissionData={PermissionManageModel.addPermissionData}
          sysNameList={GlobalEnumModel.sysNameList}
          saveForm={form => { this.addPermissionForm = form }}
          visible={PermissionManageModel.showAddPermission}
          confirmLoading={addPermissionLoading}
          onCancel={() => {
            dispatch({ type: 'PermissionManageModel/save', payload: { showAddPermission: false } });
            this.addPermissionForm.resetFields();
          }}
          onOk={permissionData => {
            dispatch({
              type: 'PermissionManageModel/addPermission',
              payload: { ...permissionData },
              successCallBack: result => {
                message.success(`新增权限成功 -> ${result.title}`);
                this.addPermissionForm.resetFields();
              },
            });
          }}
        />
        <PermissionManageUpdate
          permissionData={PermissionManageModel.updatePermissionData}
          sysNameList={GlobalEnumModel.sysNameList}
          saveForm={form => { this.updatePermissionForm = form }}
          queryLoading={getPermissionModelLoading}
          visible={PermissionManageModel.showUpdatePermission}
          confirmLoading={updatePermissionLoading}
          onCancel={() => {
            dispatch({ type: 'PermissionManageModel/save', payload: { showUpdatePermission: false } });
            this.updatePermissionForm.resetFields();
          }}
          onOk={(permissionStr, permissionData) => {
            dispatch({
              type: 'PermissionManageModel/updatePermission',
              payload: { ...permissionData, oldPermissionStr: permissionStr },
              successCallBack: result => {
                message.success(`更新权限成功 -> ${result.title}`);
                this.updatePermissionForm.resetFields();
              },
            });
          }}
        />
      </PageHeaderLayout>
    );
  }
}
